package com.dtlaya.allutils.dcmThreadUploadInsertDatebase.service;

import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class DicomStorageService {

    private final Path basePath = Paths.get("d:/var/www/pcas/uploads");
    
    // 使用内存映射文件加速大文件写入
    public Path storeDicomFile(MultipartFile file, Attributes attributes) throws IOException {
        // 生成存储路径
        Path storagePath = generateStoragePath(attributes);
        
        // 确保目录存在
        if (!Files.exists(storagePath.getParent())) {
            Files.createDirectories(storagePath.getParent());
        }
        
        // 使用直接文件传输（避免内存缓冲）
        file.transferTo(storagePath);
        
        return storagePath;
    }

    private Path generateStoragePath(Attributes attributes) {
        String studyDate = attributes.getString(Tag.StudyDate, "UNKNOWN_DATE");
        String modality = attributes.getString(Tag.Modality, "UNKNOWN_MODALITY");
        String patientID = attributes.getString(Tag.PatientID, "UNKNOWN_PATIENT");
        String studyInstanceUID = attributes.getString(Tag.StudyInstanceUID, "UNKNOWN_STUDY");
        String seriesNum = attributes.getString(Tag.SeriesNumber, "0");
        
        // 清理路径组件
        studyDate = sanitize(studyDate);
        modality = sanitize(modality);
        patientID = sanitize(patientID);
        studyInstanceUID = sanitize(studyInstanceUID);
        seriesNum = sanitize(seriesNum);
        
        // 构建路径
        return basePath.resolve(
            Paths.get(studyDate, modality, patientID, studyInstanceUID, seriesNum)
        ).resolve(generateUniqueFileName());
    }
    
    private String sanitize(String input) {
        return input.replaceAll("[\\\\/:*?\"<>|]", "_");
    }
    
    private String generateUniqueFileName() {
        return UUID.randomUUID() + ".dcm";
    }
}